package com.gobang.common.util;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 认证上下文工具类
 * 用于获取当前用户信息
 * 
 * @author System
 * @since 1.0.0
 */
public class AuthContextHolder {

    /**
     * 获取当前用户ID
     *
     * @return 用户ID
     */
    public static Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new SecurityException("用户未认证");
        }
        
        // 假设Principal是用户ID的字符串形式
        String principal = authentication.getName();
        try {
            return Long.valueOf(principal);
        } catch (NumberFormatException e) {
            throw new SecurityException("无效的用户ID格式: " + principal);
        }
    }

    /**
     * 获取当前用户名
     *
     * @return 用户名
     */
    public static String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new SecurityException("用户未认证");
        }
        
        return authentication.getName();
    }

    /**
     * 检查用户是否已认证
     *
     * @return 是否已认证
     */
    public static boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && authentication.isAuthenticated();
    }
} 